<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ManagerAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next, $role = '')
    {
        $user = $request->user();

        if ($user->status != 1) {
            return response()->json([
                'code' => 403,
                'msg' => '非常正常用户状态'
            ], 403);
        }

        if ($user->isSupper()) {
            return $next($request);
        }

        if (empty($role) && $user->is_manager) {
            return $next($request);
        }

        if ($role == 'root' && $user->isRootManager()) {
            return $next($request);
        }

        return response()->json([
            'code' => 403,
            'msg' => '无权限'
        ], 403);
    }
}
